/**
 * 
 */
package com.zznode.client.wlanpolling;

import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import android.app.Application;
import android.os.Environment;
import android.widget.Toast;

import com.zznode.client.wlanpolling.model.WebSiteManager;
import com.zznode.client.wlanpolling.service.NetworkProber;
import com.zznode.client.wlanpolling.service.net.HttpExecutorFactory;

import de.mindpipe.android.logging.log4j.LogConfigurator;

/**
 * @author Bean
 *
 */
public class WLANPollingApplication extends Application {
	private static Logger logger = Logger.getLogger(WLANPollingApplication.class);
	
	private WLanContext context;
	
	@Override
	public void onCreate() {
		super.onCreate();
		context = new WLanContext();
		context.setStatus(0);
		
		WebSiteManager.init(this);
		HttpExecutorFactory.init(this);
		
		//配置Log
        final LogConfigurator logConfigurator = new LogConfigurator();
        Date currDate = Calendar.getInstance().getTime();
        String date = (currDate.getYear() + 1900) + "-" + (currDate.getMonth()+1) + "-" + currDate.getDate();
        logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "wlanpolling_" + date + ".log");
        logConfigurator.setRootLevel(Level.DEBUG);
        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.configure();
        
		//设置通用的异常处理
		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread thread, Throwable exp) {
				NetworkProber prober = new NetworkProber(WLANPollingApplication.this);
				if(!prober.isWifi()) {
					Toast.makeText(WLANPollingApplication.this, "当前网络不可用或者不是WIFI网络,请确认网络环境必须是WIFI网络", Toast.LENGTH_LONG);
				} else {
					Toast.makeText(WLANPollingApplication.this, exp.getMessage(), Toast.LENGTH_LONG);
				}
				
				logger.error(exp.getMessage(), exp);
			}
		});
		
		logger.info("start wlan polling client.");
	}

	@Override
	public void onTerminate() {
		logger.info("terminate wlan polling client.");
		super.onTerminate();
	}

	public WLanContext getContext() {
		return context;
	}
}
